package com.tanhua.mongo.api;

import com.tanhua.api.service.FriendApi;
import com.tanhua.model.mongo.Friend;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;
import java.util.stream.Collectors;

@DubboService
public class FriendApiImpl implements FriendApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void saveFriend(Long userId, Long toUserId) {
        // 添加好友数据，需要双向添加
        Query query1 = new Query(Criteria
                .where("userId").is(toUserId)
                .and("friendId").is(userId));
        // 判断好友是否存在
        if (!mongoTemplate.exists(query1, Friend.class)) {
            Friend friend = new Friend();
            friend.setFriendId(userId);
            friend.setUserId(toUserId);
            friend.setCreated(System.currentTimeMillis());

            mongoTemplate.save(friend);
        }

        Query query2 = new Query(Criteria
                .where("userId").is(userId)
                .and("friendId").is(toUserId));

        if (!mongoTemplate.exists(query2, Friend.class)) {
            Friend friend = new Friend();
            friend.setFriendId(toUserId);
            friend.setUserId(userId);
            friend.setCreated(System.currentTimeMillis());

            mongoTemplate.save(friend);
        }


    }

    @Override
    public List<Long> findByToUserId(Long userId) {

        List<Friend> list = mongoTemplate.find(new Query(Criteria
                .where("userId").is(userId)), Friend.class);

        return list.stream().map(Friend::getFriendId).collect(Collectors.toList());
    }

    @Override
    public void deleteFriend(Long userId, Long friendId) {

        Query query1 = Query.query(Criteria
                .where("userId").is(userId)
                .and("friendId").is(friendId));

        if (mongoTemplate.exists(query1, Friend.class)) {
            mongoTemplate.remove(query1, Friend.class);
        }

        Query query2 = Query.query(Criteria
                .where("userId").is(friendId)
                .and("friendId").is(userId));

        if (mongoTemplate.exists(query2, Friend.class)) {
            mongoTemplate.remove(query2, Friend.class);
        }



    }
}
